//
//  TXSwiftAbstractFooterView.swift
//  TXiOSDemoApp
//
//  Created by xicheng on 16/11/25.
//  Copyright © 2016年 xicheng. All rights reserved.
//

import UIKit



public enum TXSwiftFooterViewStatus:String {
  case normal // 正常
  
  case prepareToLoading // 加载更多
  
  case loadingMore // 刷新中
  
  case noMoreData //没有更多的数据
}


open class TXSwiftAbstractFooterView: UIView {

  private weak var scrollView:UIScrollView? = nil
  
  private var loadMoreAction:(()->())? = nil
  
  private var TXFooterKVOContext = "TXFooterKVOContext"
  
  
  internal var originalScrollViewInsets:UIEdgeInsets = UIEdgeInsets.zero
  
  public var footerViewStatus:TXSwiftFooterViewStatus = .normal {
    
    didSet{
      
      switch footerViewStatus {
      case .normal:
        break
      case .prepareToLoading:
        break
      case .loadingMore:
        break
      case .noMoreData:
        break
      }
      self.footerViewStatusListener?(footerViewStatus)
    }
    
  }
  
  private lazy var footerViewStatusListener:((TXSwiftFooterViewStatus)->Void)? = {
    [unowned self] in
    return self.configFooterViewStatusListener()
    }()
  
  private lazy var TX_footerViewPullHeight:CGFloat = {
    [unowned self] in
    return self.configLoadMorePullHeight()
    }()
  
  
  
  
  public required init(action:@escaping (()->Void),frame: CGRect) {
    super.init(frame: frame)
    self.prepareView()
    self.loadMoreAction = action
  }
  
  required public init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
  
  open func configLoadMorePullHeight()->CGFloat{
    return 50.0
  }
  
  open func configFooterViewStatusListener()->((TXSwiftFooterViewStatus)->Void)? {
    return nil
  }
  
  
  open func prepareView(){
    
  }
  
  
  func startAnimation(){
    
  }
  
  func stopAnimation(){
    
//    UIView.animate(withDuration: 0.25, animations: {
//      [unowned self] in
//      
//      guard let scrollView = self.scrollView else {
//        return
//      }
//      
//      //      if (abs(scrollView.contentOffset.y) >= self.TX_headerPullHeight){
//      scrollView.contentInset = UIEdgeInsetsMake(scrollView.contentInset.top - self.TX_footerViewPullHeight, 0, scrollView.contentInset.bottom, 0)
//      //      }
//    }) { [unowned self](flag) in
//      self.footerViewStatus = .normal
//      self.scrollView?.tx_refreshStatus = .normal
//    }
    
  }
  
  
  
  open override func willMove(toSuperview newSuperview: UIView?) {
    super.willMove(toSuperview: newSuperview)
    superview?.removeObserver(self, forKeyPath: TX_contentOffsetKeyPath, context: &TXFooterKVOContext)
    superview?.removeObserver(self, forKeyPath: TX_contentSizeKeyPath, context: &TXFooterKVOContext)
    if let scrollView = newSuperview as? UIScrollView {
      self.scrollView = scrollView
      self.originalScrollViewInsets = scrollView.contentInset
      let offSet:CGFloat = 0
      let oldContentInset = self.originalScrollViewInsets 
      self.scrollView!.contentInset = UIEdgeInsetsMake(oldContentInset.top, oldContentInset.left, oldContentInset.bottom + self.frame.height + offSet + self.scrollView!.frame.origin.y , oldContentInset.right)
      
      newSuperview?.addObserver(self, forKeyPath: TX_contentOffsetKeyPath, options: .initial, context: &TXFooterKVOContext)
      newSuperview?.addObserver(self, forKeyPath: TX_contentSizeKeyPath, options: .initial, context: &TXFooterKVOContext)
    }
    
  }
  
  open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    
    
    
    guard let scrollView = self.scrollView else {
      return
    }
    
    if keyPath == TX_contentSizeKeyPath {
      
      if let collectionView = scrollView as? UICollectionView {
        let height = collectionView.collectionViewLayout.collectionViewContentSize.height
        self.frame.origin.y = height
      }else {
        if scrollView.contentSize.height == 0 {
          self.frame.origin.y = 0
        }else if scrollView.contentSize.height < self.frame.size.height {
          self.frame.origin.y = scrollView.frame.size.height - self.frame.height
        }else {
          self.frame.origin.y = scrollView.contentSize.height
        }
      }
      
      TXLogWarn("FooterView_frame更改:\(self.frame)")
      return
    }
    
    guard scrollView.tx_refreshStatus != TXRefreshStatus.noMoreData else {
      return
    }
    
    let offSet_Y = scrollView.contentOffset.y
    
    guard let action = self.loadMoreAction else {
      return
    }
    
    if scrollView.tx_refreshStatus == TXRefreshStatus.loadMore {
      if self.footerViewStatus != .loadingMore {
        TXLogError("ScrollView与HeaderView状态不匹配：\(self.footerViewStatus)")
      }
      
      return
    }
    
    
    
    TXLogDebug("HeaderView:\(offSet_Y)")
    
    if offSet_Y > 0 {
      let newOffSet_Y = offSet_Y + scrollView.frame.height
      var tableViewMaxHeight:CGFloat = 0
      if let collectionView = scrollView as? UICollectionView {
        let height = collectionView.collectionViewLayout.collectionViewContentSize.height
        tableViewMaxHeight = height
      
      }else if scrollView.contentSize.height > 0 {
        tableViewMaxHeight = scrollView.contentSize.height
      }
      let draggingFlag = scrollView.isDragging
      if (newOffSet_Y - tableViewMaxHeight) > 0 {
        
        if draggingFlag {
          if self.footerViewStatus == .normal {
            self.configSelf(WithStatus: TXSwiftFooterViewStatus.prepareToLoading)
          }
        }else {
          self.configSelf(WithStatus: TXSwiftFooterViewStatus.loadingMore)
          if scrollView.tx_refreshStatus != TXRefreshStatus.loadMore {
            scrollView.tx_refreshStatus = TXRefreshStatus.loadMore
            action()
          }

        
        }
      
      }else {
        self.configSelf(WithStatus: .normal)
      }
      
    }
    
  }
  
  private func configSelf(WithStatus status:TXSwiftFooterViewStatus){
    if self.footerViewStatus != status {
      self.footerViewStatus = status
      TXLogInfo("FooterStatus更换为：\(status)")
    }
  }
  
  
  deinit {
    if let parentView = superview as? UIScrollView {
      parentView.removeObserver(self, forKeyPath: TX_contentOffsetKeyPath, context: &TXFooterKVOContext)
    }
  }

  
}
